package com.atguigu.chapter07.D02_WaterMark;

import com.atguigu.bean.WaterSensor;
import com.atguigu.util.AnqclnUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * Author: Pepsi
 * Date: 2023/8/5
 * Desc:
 *
 * 进入哪个窗口看事件事件
 * 窗口啥时候关闭看水印 [)  前闭后开
 *
 * 水印可以解决数据的乱序问题
 *
 */
public class Flink01_WaterMark_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);

        env
                .socketTextStream("hadoop101",9999)
                .map(line->{
                    String[] data = line.split(",");
                    return new WaterSensor(
                            data[0],
                            Long.valueOf(data[1]),
                            Integer.valueOf(data[2])
                    );
                })
                // 加水印  分配时间戳和水印
                .assignTimestampsAndWatermarks(
                        // 水印策略
                        WatermarkStrategy
                                // 对于乱序的  最大乱序程度     乱3秒    告诉水印怎么生成
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                // 告诉了最大乱序程度后，还必须告诉时间戳，因为水印的计算是用最大事件时间减去乱序程度再减去1毫秒
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                                    // 这个方法返回一个long类型的毫秒值，作为这条数据的时间戳
                                    // 第一个参数就是传过来的元素。从元素中搞出一个时间作为这个元素的事件时间
                                    // 第二个参数是前面的水印，其实没用
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        // 事件时间是谁
                                        return element.getTs();
                                    }
                                })
                )
                .keyBy(WaterSensor::getId)
                //  用滚动的事件窗口
                .window(TumblingEventTimeWindows.of(Time.seconds(5)))
                .process(new ProcessWindowFunction<WaterSensor, String, String, TimeWindow>() {
                    @Override
                    public void process(String s, Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                        List<WaterSensor> list = AnqclnUtil.toList(elements);
                        String startTime = AnqclnUtil.toDateTime(context.window().getStart());
                        String endTime = AnqclnUtil.toDateTime(context.window().getEnd());
                        out.collect(s+" "+startTime+" "+endTime+" "+list);
                    }
                })
                .print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
